package luob.common;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by luob on 15/6/13.
 */
@Before(ManagerInterceptor.class)
public class MyBaseController extends Controller {
    private Map<String, Object> attrs = new HashMap<String, Object>();

    protected void addAttr(String key, Object value) {
        attrs.put(key, value);
    }

    protected void setCtrlFlow(String[] flow) {
        setAttr("ctrl_flow", flow);
    }

    protected void handleResult() {
        String[] flow = getAttr("ctrl_flow");
        int index = getAttr("ctrl_flow_index") == null ? 0
                : getAttrForInt("ctrl_flow_index");
        if (null != flow && index < flow.length) {
            setAttr("ctrl_flow_index", index + 1);
            for (String key : attrs.keySet()) {
                setAttr("JSON" + index + "_" + key, JsonKit.toJson(attrs.get(key)));
                setAttr("OBJ" + index + "_" + key, attrs.get(key));
            }
            if (flow[index].contains(".html")) {
                render(flow[index]);
            } else {
                forwardAction(flow[index]);
            }
        } else {
            for (String key : attrs.keySet()) {
                setAttr(key, attrs.get(key));
            }
            renderJson();
        }
    }

    protected void toNextFlow() {
        String[] flow = getAttr("ctrl_flow");
        int index = getAttr("ctrl_flow_index") == null ? 0
                : getAttrForInt("ctrl_flow_index");
        if (null != flow && index < flow.length) {
            setAttr("ctrl_flow_index", index + 1);
            if (flow[index].contains(".html")) {
                render(flow[index]);
            } else {
                forwardAction(flow[index]);
            }
        }
    }
}
